package main

import (
	"fmt"
	"log"
	"time"
)

var stop1 = make(chan bool, 1)
var c1 = make(chan string, 1)

func routine1() {
	log.Println("start r1")
	defer recoverPanic()
Loop:
	for {
		select {
		case msg := <-c1:
			log.Printf("r1 get msg %s \n", msg)
		case stop := <-stop1:
			if stop {
				log.Println("r1 will stop ...")
				break Loop
			}
		case <-time.After(time.Second * 1):
			log.Println("r1 timeout ")
			//panic("aaaa")
		}
	}
	stop1 <- true
	log.Println("stop r1")
}

func recoverPanic() {
	log.Println("recover panic")
	if err := recover(); err != nil {
		log.Printf("panic info %s", err)
	}
	log.Println("recover done")
}
func routine2() {
	log.Println("start r2")
	for i := 0; i < 100; i++ {
		msg := fmt.Sprintf("msg %d", i)
		if i%10 == 0 {
			time.Sleep(time.Second * 2)
		}
		select {
		case c1 <- msg:
		default:
			log.Println("c1 is full! ")
		}

	}
	stop1 <- true
	log.Println("stop r2 ")
}

func main() {
	go routine1()
	go routine2()
	<-stop1
	log.Println("stop main ")
}
